#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import logging
import re
import typing

class GnCommon:
    def find_files(self,
                   project_path: str,
                   target_filename: str = "BUILD.gn",
                   black_keywords: tuple = tuple(),
                   black_dirs: tuple = tuple()) -> set:
        cmd = "find {} -name {}".format(project_path,
                                        target_filename)
        result_set = set()
        for bd in black_dirs:
            cmd += " ! -path \"./{}/*\"".format(bd)
        output = os.popen(cmd)
        for file in output:
            if GnCommon.contains_keywords(black_keywords, file):
                continue
            result_set.add(file.strip())
        logging.info("total: {}".format(len(result_set)))
        return result_set

    def find_paragraph_iter(self, start_parttern: str, end_pattern: str,
                            content: str) -> typing.Iterator:
#pattern = r"^( *){}[\s|\S]*?\n\1{}$".format(start_parttern, end_pattern)
#        pattern = r"^( *){}.*\1{}$".format(start_parttern, end_pattern)
#        ptrn = re.compile(pattern, flags = re.S | re.M)
#        result = re.finditer(ptrn, content)
        
        return result

    def scan(self, input_fileset, handler):
        # add common subsystem info
        for f in input_fileset:
            handler(f)
